#ifndef LOGS_H
#define LOGS_H
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QDebug>
#include <QFile>
#include <memory>
#include <QObject>
#include <QVariant>
#include <QMap>
#include <QMutex>
#include <QMutexLocker>

class Logs
{
public:
    Logs();
};

static Logs* log=new Logs();

class JsonConfigManager
{
public:
    // 获取单例实例
    static JsonConfigManager* instance() {
        static JsonConfigManager* instance=new JsonConfigManager();
        return instance;
    }

    // 初始化配置文件
    bool initialize(const QString& configFilePath) {
        QMutexLocker locker(&m_mutex);
        m_configFilePath = configFilePath;
        locker.unlock();
        return reloadFromFile();
    }

    // 获取配置值
    QVariant get(const QString& key, const QVariant& defaultValue) {
        QMutexLocker locker(&m_mutex);

        // 如果key存在直接返回值
        if (m_configMap.contains(key)) {
            return m_configMap.value(key);
        }

        // 不存在时设置默认值并返回
        m_configMap.insert(key, defaultValue);
        m_dirty = true;  // 标记配置有更新

        // 将默认值同步到JSON对象
        QJsonValue jsonValue;
        if (defaultValue.type() == QMetaType::QString) {
            jsonValue = defaultValue.toString();
        } else if (defaultValue.type() == QMetaType::Int ||
                  defaultValue.type() == QMetaType::LongLong) {
            jsonValue = defaultValue.toInt();
        } else if (defaultValue.type() == QMetaType::Double) {
            jsonValue = defaultValue.toDouble();
        } else if (defaultValue.type() == QMetaType::Bool) {
            jsonValue = defaultValue.toBool();
        } else {
            jsonValue = QJsonValue::fromVariant(defaultValue);
        }

        m_jsonObject.insert(key, jsonValue);
        return defaultValue;
    }

    // 设置配置值
    void set(const QString& key, const QVariant& value) {
        QMutexLocker locker(&m_mutex);
        m_configMap.insert(key, value);
        m_jsonObject.insert(key, QJsonValue::fromVariant(value));
        m_dirty = true;
    }

    // 立即保存配置到文件
    bool save() {
        QMutexLocker locker(&m_mutex);
        if (!m_dirty) return true;  // 无修改无需保存

        QFile file(m_configFilePath);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
            qWarning() << "Failed to open config file for writing:" << m_configFilePath;
            return false;
        }

        QJsonDocument doc(m_jsonObject);
        if (file.write(doc.toJson()) == -1) {
            qWarning() << "Failed to write config file:" << file.errorString();
            file.close();
            return false;
        }

        file.close();
        m_dirty = false;
        return true;
    }

    // 重新加载配置文件
    bool reloadFromFile() {
        QMutexLocker locker(&m_mutex);

        QFile file(m_configFilePath);
        if (!file.exists()) {
            qWarning() << "Config file not exists, will create new one:" << m_configFilePath;
            locker.unlock();
            return save();  // 创建新文件
        }

        if (!file.open(QIODevice::ReadOnly))
        {
            qCritical() << "Failed to open config file:" << m_configFilePath;
            locker.unlock();
            return false;
        }

        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &parseError);
        file.close();

        if (parseError.error != QJsonParseError::NoError) {
            qCritical() << "JSON parse error:" << parseError.errorString();
            return false;
        }

        if (!doc.isObject()) {
            qCritical() << "Config file is not a JSON object";
            return false;
        }

        m_jsonObject = doc.object();
        m_configMap.clear();

        // 将JSON对象转换为内存映射
        for (auto it = m_jsonObject.begin(); it != m_jsonObject.end(); ++it) {
            m_configMap.insert(it.key(), it.value().toVariant());
        }

        m_dirty = false;
        return true;
    }

private:
    explicit JsonConfigManager(){}
    ~JsonConfigManager() {
        save(); // 确保析构时保存配置
    }

    // 禁止复制

    QMutex m_mutex;
    QString m_configFilePath;
    QJsonObject m_jsonObject;
    QMap<QString, QVariant> m_configMap;
    bool m_dirty = false;
};

#endif // LOGS_H
